package com.myblog.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.myblog.common.CommonConstant;
import com.myblog.common.ResultInfoFactory;
import com.myblog.service.SmsSend;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@Slf4j
public class CustomLoginController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    SmsSend smsSend;

    @RequestMapping("/login/page")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/mobile/page")
    public String toMobilePage(){
        return "login-mobile";
    }

    @ResponseBody
    @RequestMapping("/code/mobile")
    public ResultInfoFactory smsCode(HttpServletRequest request){
        String code = RandomStringUtils.randomNumeric(4);
        request.getSession().setAttribute(CommonConstant.SESSION_KEY_MOBILE,code);
        String mobile = request.getParameter("mobile");
        smsSend.sendSms(mobile,code);
        return ResultInfoFactory.success();
    }

    @RequestMapping("/code/image")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String text = defaultKaptcha.createText();
        log.info("生成的图形验证码是={}",text);
        request.getSession().setAttribute(CommonConstant.SESSION_KEY,text);
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
    }


}
